package okhttp3.internal.platform.ohos;

import okhttp3.Protocol;
import okhttp3.internal.platform.BouncyCastlePlatform;
import org.bouncycastle.jsse.BCSSLParameters;
import org.bouncycastle.jsse.BCSSLSocket;
import org.conscrypt.Conscrypt;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.util.List;

import static okhttp3.internal.platform.Platform.alpnProtocolNames;

public class BouncyCastleSocketAdapter implements SocketAdapter {
    private static final DeferredSocketAdapter.Factory factory = (DeferredSocketAdapter.Factory) (new DeferredSocketAdapter.Factory() {
        public Boolean matchesSocket(SSLSocket sslSocket) {
            return BouncyCastlePlatform.Companion.isSupported() && Conscrypt.isConscrypt(sslSocket);
        }

        public SocketAdapter create(SSLSocket sslSocket) {
            return (SocketAdapter) (new ConscryptSocketAdapter());
        }
    });

    @Override
    public Boolean isSupported() {
        return BouncyCastlePlatform.Companion.isSupported();
    }

    @Override
    public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
        return null;
    }

    @Override
    public Boolean matchesSocket(SSLSocket sslSocket) {
        return sslSocket instanceof BCSSLSocket;
    }

    @Override
    public Boolean matchesSocketFactory(SSLSocketFactory sslSocketFactory) {
        return null;
    }

    @Override
    public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
        if (this.matchesSocket(sslSocket)) {
            BCSSLSocket bcSocket = (BCSSLSocket) sslSocket;
            BCSSLParameters sslParameters = bcSocket.getParameters();
            List names = alpnProtocolNames(protocols);
            Object[] objects = new Object[names.size()];
            names.toArray(objects);
            sslParameters.setApplicationProtocols((String[]) objects);
            bcSocket.setParameters(sslParameters);
        }
    }

    @Override
    public String getSelectedProtocol(SSLSocket sslSocket) {
        BCSSLSocket s = (BCSSLSocket) sslSocket;
        String protocol = s.getApplicationProtocol();
        String string;
        if (protocol != null) {
            switch (protocol.hashCode()) {
                case 0:
                    if (protocol.equals("")) {
                        break;
                    }
                default:
                    string = protocol;
                    return string;
            }
        }

        string = null;
        return string;
    }

    class Companion {
        public final DeferredSocketAdapter.Factory getFactory() {
            return BouncyCastleSocketAdapter.factory;
        }

        public SocketAdapter create(SSLSocket sslSocket) {
            return BouncyCastleSocketAdapter.this;
        }

        private Companion() {
        }
    }
}
